/*
 *	DjoltContext.m
 *
 *	David Janes
 *	Discover Anywhere Mobile
 *	March 2010
 *
 *	Copyright 2010 Discover Anywhere Mobile
 */

#import "DjoltContext.h"

@implementation DjoltContext
@synthesize stack;

- (id) init
{
	return	[self initWithDictionary:nil];
}

- (id) initWithDictionary:(NSDictionary*)_d
{
    if (self = [super init]) {
		stack = [[NSMutableArray alloc] initWithCapacity: 0];

		if (_d) {
			[stack addObject:[[NSMutableDictionary alloc] initWithDictionary:_d]];
		}
	}

	return	self;
}

- (void) push
{
	[stack addObject:[[NSMutableDictionary alloc] initWithCapacity:0]];
}

- (void) pop
{
	[stack removeLastObject];
}

- (void) setObject:(id)_object forKey:(id)_key
{
	[[stack lastObject] setObject:_object forKey:_key];
}

- (id) get:(NSString*)_path
{
	int i = 0;
	for (i = [self.stack count] - 1; i >= 0; i--) {
		id v = [[self.stack objectAtIndex:i] valueForKeyPath:_path];
		if (v) {
			return	v;
		}
	}

	return	nil;
}

- (BOOL) getBool:(NSString*)_path otherwise:(BOOL)_otherwise
{
	id _value = [self get:_path];
	if (_value == nil) {
		return	_otherwise;
	}

	if ([_value isKindOfClass:[NSNumber class]]) {
		return	[_value boolValue];
	} else if ([_value isKindOfClass:[NSString class]]) {
		return	[_value length];
	} else if ([_value isKindOfClass:[NSDictionary class]]) {
		return	[_value count];
	} else if ([_value isKindOfClass:[NSArray class]]) {
		return	[_value count];
	} else {
		return	_otherwise;
	}
}

- (NSString*) getString:(NSString*)_path otherwise:(NSString*)_otherwise
{
	id _value = [self get:_path];
	if (_value == nil) {
		return	_otherwise;
	}

	if ([_value isKindOfClass:[NSString class]]) {
		return	_value;
	} else if ([_value isKindOfClass:[NSNumber class]]) {
		return	[NSString stringWithFormat:@"%@", _value];
	} else {
		return	_otherwise;
	}
}

- (NSArray*) getArray:(NSString*)_path otherwise:(NSArray*)_otherwise
{
	id _value = [self get:_path];
	if (_value == nil) {
		return	_otherwise;
	}

	if ([_value isKindOfClass:[NSArray class]]) {
		return	_value;
	} else {
		return	_otherwise;
	}
}
@end
